/**
 * Created by zwxu on 2017/4/5.
 */
$(function() {
	initTable();
	initDialog();
	initQuery();
	
	$("#upload_btn").on("click", function() {
		openRoleDialog("add", null);
	});
	
	$("#menu_form").validate({
		rules : {
			name : "required"
		},
		messages : {
			name : "请输入菜单名称"
		},
		submitHandler : function() {
			var id = $("#dialog_id").val();
			if(id == null || id == ""){
				menuDialogAdd();
			}else{
				menuDialogEdit();
			}	
		}
	});
})
function openRoleDialog(type,data){	
	var c = $("#dialog_parent").empty();
	c.append("<option value=''>选择父菜单</option>");
	$.ajax({
		type : "POST",
		url : ctx + "/web/menu/getParentMenu",
		async : false,
		success : function(data) {
			$.each(data, function(i, a) {
				c.append("<option value='{0}'>{1}</option>".format(a.id,
						a.name));
			});
		}
	});
	
	if (!$.isEmptyObject(type) && type == "add") {
		$("#menu_dialog").dialog('option', 'title', "新增菜单");
		$("#menu_dialog").dialog({
			buttons : {
				"取消" : function() {
					$(this).dialog("close");
				}
			}
		});
	} else {
		$("#menu_dialog").dialog('option', 'title', "编辑菜单");
		$("#menu_dialog").dialog({
			buttons : {
				"取消" : function() {
					$(this).dialog("close");
				}
			}
		});
		if(data.parentId == null || data.parentId == ""){
			$("#form_url").hide();
			$("#form_parent").hide();
		}else{
			$("#form_url").show();
			$("#form_parent").show();
		}
		$("#dialog_id").val(data.id);
		$("#dialog_name").val(data.name);
		$("#dialog_url").val(data.url);
		$("#dialog_parent").val(data.parentId);
	}
	$("#menu_dialog").dialog('open');
}

function initQuery() {
	$("#menu_query_btn").click(function() {
		table.fnDraw();
	});
}
function initDialog(){
	$("#menu_dialog").dialog({
		 autoOpen : false,
	      resizable: false,
	      height:500,
	      width:500,
	      modal: true,
			close : function(e, u) {
				$(this).find(".text-error").remove();
				$(this).find(":text,:hidden,select").val("");
				$(this).find("select > option").remove();
			}
	    });
}
/**
 * http://yuemeiqing2008-163-com.iteye.com/blog/2006942
 * @desc 初始化表格  DataTable.defaults = api参数看这里
 */
function initTable() {
	
	table=$('#dynamic-table')
			.dataTable(
					{
						"bInfo" : true,
						"bServerSide" : true,
						"bPaginate" : true,
						"bFilter" : false,
						"aaSorting" : [],
						"bProcessing" : false,
						"bLengthChange" : true,
						"iDisplayLength" : 10,
						"aLengthMenu" : [ [ 10, 20, 50, 500, 1000 ],
								[ 10, 20, 50, 500, 1000 ] ],
						"sPaginationType" : "full_numbers",
						"bStateSave" : false,
						"bAutoWidth" : false,
						"sDom" : '<"top"f>r<"datatable-scroll"t><"datatable-bottom"lip>',
						"oLanguage" : {
							"sLengthMenu" : "<div style='float:left;margin-left:0px;'>_MENU_</div>",
							"sZeroRecords" : "抱歉， 没有找到",
							"sInfo" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
							"sInfoEmpty" : "共 0 条数据/共 0 页！",
							"sInfoFiltered" : "(filtered from _MAX_ total records)",
							"sProcessing" : "加载中...",

							oPaginate : {
								sPrevious : "上一页",
								sNext : "下一页",
								sFirst : "首页",
								sLast : "尾页"
							}
						},
						"sAjaxSource" : ctx + "/web/menu/list",
						 "sServerMethod": "POST" ,
						 "sSearch" : "搜索",   
						//服务器端，数据回调处理  
                        "fnServerData" : function(sSource, aDataSet, fnCallback) {  
                        	
                            $.ajax({  
                                "dataType" : 'json',  
                                "type" : "POST",  
                                "url" : sSource,  
                                "data" : aDataSet,  
                                "success" : fnCallback  
                            });   
                        	},
						"fnServerParams" : function (aoData) {
							
		                    aoData.push(
		                        { "name": "name", "value": $("#name").val() }
		                    );
		                }, 
		                "fnDrawCallback": function( oSettings ) {
		                	//console.log( 'DataTables 重绘了' + oSettings.aoServerParams.name);
		                  },
		                  "aoColumnDefs": [{
		                      "render": function(data, type, row) {
		                    	  var val = row[4];
								  return "<a href='javascript:;' onclick='editRole({0})'>编辑</a>"
											.format(val);
		                      },
		                      "targets":  4
		                  },{
		                      "render": function(data, type, row) {
		                    	  var val = row[5];
									return "<a href='javascript:;' onclick='deleteRole({0})'>删除</a>"
											.format(val);
		                      },
		                      "targets": 5
		                  }],
						"aoColumns" : [{		         
			                 "bSortable": false
			             }, {
							sName : "id",
							"bSortable": true
						}, {
							sName : "name"
						} ]
					});
	var tableSetings=$('#dynamic-table').dataTable().fnSettings()  
	//console.log(tableSetings);
}
function editRole(id) {
	$.ajax({
		url : ctx + '/web/menu/getById',
		type : "post",
		data : {
			id : id
		},
		success : function(data) {
			if (data) {
				openRoleDialog("edit", data);
			} else {
				myalert(null, "获取组件信息失败！");
			}
		},
		error : function() {
			errorPrompt("#menu_dialog", "获取组件信息出错");
		}
	});
}
/**
 * @desc 删除接口
 * @arg {long}id
 * @return{string} 返回提示信息
 */
function deleteRole(id) {
	myConfirm('', '确定要删除', function() {
		$.ajax({
			url : ctx + '/web/menu/delete',
			type : 'POST',
			data : {
				id : id
			},
			success : function(data) {
				if (data) {
					myalert(null, data);
				} else {
					table.fnDraw();
				}
			}
		});
	});
}
function menuDialogAdd() {
	var param = $("#menu_form").serialize();
	console.log(param);
	$.ajax({
		url : ctx + '/web/menu/save',
		type : "post",
		data : param,
		success : function(data) {
			if (data) {
				errorPrompt("#menu_dialog", data);
			} else {
				$("#menu_dialog").dialog("close");
				table.fnDraw();
			}
		},
		error : function() {
			errorPrompt("#menu_dialog", "保存出错");
		}
	});
}
/**
 * @desc 编辑组件
 * @return{string} 返回提示信息
 */
function menuDialogEdit() {
	var param = $("#menu_form").serialize();
	$.ajax({
		url : ctx + '/web/menu/update',
		type : "post",
		data : param,
		success : function(data) {
			if (data) {
				errorPrompt("#menu_dialog", data);
			} else {
				$("#menu_dialog").dialog("close");
				table.fnDraw();
			}
		},
		error : function() {
			errorPrompt("#menu_dialog", "编辑出错");
		}
	});
}